package com.sh.sales.happysales.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sh.polymedicine.happysale.result.SimpleResult;
import com.sh.polymedicine.happysale.result.UserInfoResult;
import com.sh.polymedicine.happysale.service.envelop.HappySaleManager;
import com.sh.sales.happysales.R;
import com.sh.sales.happysales.adapter.MineMenuAdapter;
import com.sh.sales.happysales.app.AppData;
import com.sh.sales.happysales.app.utils.LoginOutUtil;
import com.sh.sales.happysales.imgutil.LoadImageManager;
import com.sh.sales.happysales.ui.activity.FeedbackActivity;
import com.sh.sales.happysales.ui.activity.SetActivity;
import com.sh.sales.happysales.ui.activity.UserInfoActivity;
import com.sh.sales.happysales.ui.activity.WalletActivity;
import com.sh.sales.happysales.view.NewToast;
import com.sh.sales.happysales.view.RoundCornersImageView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Subscriber;

/**
 * Created by zhouyucheng on 2017/9/15.
 */

public class MineFragment extends Fragment {
    private String TAG = "MineFragment";
    @BindView(R.id.mine_set)
    TextView mineSet;
    @BindView(R.id.mine_userimage)
    RoundCornersImageView mineUserimage;
    @BindView(R.id.user_nick)
    TextView userNick;
    @BindView(R.id.lin_usernick)
    LinearLayout linUsernick;
    @BindView(R.id.mine_menu)
    GridView mineMenu;
    @BindView(R.id.mine)
    LinearLayout linMine;
    Unbinder unbinder;
    private String[] strMenus = {"我的钱包", "QQ群", "用户反馈"};
    private int[] imgMenus = {R.drawable.icon_mypagage, R.drawable.cion_qqgroup, R.drawable.cion_usefeedback};
    private View inflate;

    private MineMenuAdapter mineMenuAdapter;
    private PopupWindow popupWindow;
    private String QQurl;
    private DisplayImageOptions qqOptions;
    private LoadImageManager mLoadImageManager;

    private Subscriber<SimpleResult> qqGroupSubscriber;
    private DisplayImageOptions headerOptions;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        inflate = inflater.inflate(R.layout.fragment_mine, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        mLoadImageManager = LoadImageManager.getInstance(getActivity());
        linMine.setFocusable(true);
        linMine.setFocusableInTouchMode(true);
        linMine.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    LoginOutUtil.appDoublebtExit(getActivity());
                    return true;
                }
                return false;
            }
        });
        headerOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_nologin)
                .showImageForEmptyUri(R.drawable.icon_nologin)
                .displayer(new RoundedBitmapDisplayer(4))
                .showImageOnFail(R.drawable.icon_nologin)
                .imageScaleType(ImageScaleType.EXACTLY)
                .considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        qqOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.bg_start_page)
                .showImageForEmptyUri(R.drawable.bg_start_page)
                .displayer(new RoundedBitmapDisplayer(4))
                .showImageOnFail(R.drawable.bg_start_page)
                .imageScaleType(ImageScaleType.EXACTLY)
                .considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        init();
        return inflate;
    }


    private void init() {
        String userSign = AppData.getInstence().getmUserToken().getUserSign();
        if (qqGroupSubscriber != null) {
            if (qqGroupSubscriber.isUnsubscribed()) {
                qqGroupSubscriber.unsubscribe();
            }
        }
        qqGroupSubscriber = new Subscriber<SimpleResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError:" + e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(getActivity(), message);
                    int ret = Integer.valueOf(e.getCause().getMessage());
                    if (ret >= 100 && ret < 200) {
                        LoginOutUtil.logOut(getActivity());
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(getActivity(), e.getCause().getMessage());
                } else {
                    NewToast.makeText(getActivity(), "获取qq群信息失败，请检查网络");
                }
            }

            @Override
            public void onNext(SimpleResult result) {
                QQurl = result.getImage();
                Log.i(TAG, "onNext: " + QQurl);
            }
        };
        HappySaleManager.getInstence().discussQq(userSign, qqGroupSubscriber).subscribe(qqGroupSubscriber);
        mineMenuAdapter = new MineMenuAdapter(strMenus, imgMenus, getActivity());
        mineMenu.setAdapter(mineMenuAdapter);
        mineMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                menuEnter(i);
            }
        });
    }

    private void initView() {
        UserInfoResult result = AppData.getInstence().getmUserInfoResult();
        userNick.setText(result.getNickname());
        LoadImageManager.getInstance(getActivity()).displayImage(result.getPortrait(), mineUserimage,
                LoadImageManager.IMG, headerOptions);
    }

    private void menuEnter(int i) {
        Intent m = new Intent();
        switch (i) {
            case 0:
                m.setClass(getActivity(), WalletActivity.class);
                startActivity(m);
                break;
            case 1:
                popQqwindow();
                break;
            case 2:
                m.setClass(getActivity(), FeedbackActivity.class);
                startActivity(m);
                break;
            default:
                NewToast.makeText(getActivity(), "升级中...", Toast.LENGTH_SHORT).show();
                break;
        }

    }

    /**
     * qq群图片
     */
    private void popQqwindow() {
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.pop_qqgroup, null);
        contentview.setFocusable(true); // 这个很重要
        contentview.setFocusableInTouchMode(true);
        popupWindow = new PopupWindow(contentview, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        ImageView img = (ImageView) contentview.findViewById(R.id.set_back);
        ImageView img_qqgroup = (ImageView) contentview.findViewById(R.id.img_qqgroup);
        mLoadImageManager.displayImage(QQurl, img_qqgroup, LoadImageManager.IMG, qqOptions);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        contentview.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    popupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        popupWindow.showAtLocation(inflate, Gravity.CENTER, 0, 0);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.mine_set, R.id.mine_userimage, R.id.lin_usernick})
    public void onViewClicked(View view) {
        Intent m = new Intent();
        switch (view.getId()) {
            case R.id.mine_set:
                m.setClass(getActivity(), SetActivity.class);
                break;
            case R.id.mine_userimage:
            case R.id.lin_usernick:
                m.setClass(getActivity(), UserInfoActivity.class);
                break;
        }
        getActivity().startActivity(m);
    }

    @Override
    public void onResume() {
        initView();
        super.onResume();
    }
}
